<template>
  <el-button @click="sendDataToServer" v-if="false">给后台发送消息测试</el-button>
</template>

<script>
  export default {
    name: 'WebSocket',
    data() {
      return {
        // ws是否启动
        wsIsRun: false,
        // 定义ws对象
        webSocket: null,
        // ws请求链接（类似于ws后台地址）
        ws: '',
        // ws定时器
        wsTimer: null,
        userId: this.$store.state.user.id,
        uri: ''
      }
    },
    mounted() {
      this.wsIsRun = true
      this.wsInit()
    },
    methods: {
      /**
       * 初始化ws
       */
      async wsInit() {
        let getConfigKey = this.getConfigKey("web.socket.uri").then(response => {
          this.uri = response.msg;
        })
        await getConfigKey;
        this.ws = this.uri + this.userId
        if (!this.wsIsRun) return
        // 销毁ws
        this.wsDestroy()
        // 初始化ws
        this.webSocket = new WebSocket(this.ws)
        // ws连接建立时触发
        this.webSocket.addEventListener('open', this.wsOpenHandle)
        // ws服务端给客户端推送消息
        this.webSocket.addEventListener('message', this.wsMessageHandle)
        // ws通信发生错误时触发
        this.webSocket.addEventListener('error', this.wsErrorHandle)
        // ws关闭时触发
        this.webSocket.addEventListener('close', this.wsCloseHandle)

        // 检查ws连接状态,readyState值为0表示尚未连接，1表示建立连接，2正在关闭连接，3已经关闭或无法打开
        clearInterval(this.wsTimer)
        this.wsTimer = setInterval(() => {
          if (this.webSocket.readyState === 1) {
            clearInterval(this.wsTimer)
          } else {
            console.log('ws建立连接失败')
            this.wsInit()
          }
        }, 3000)
      },
      wsOpenHandle(event) {
        console.log('ws建立连接成功')
      },
      wsMessageHandle(e) {
        let that = this
        let msg = JSON.parse(e.data)
        this.$notify.info({
          title: msg.title,
          message: msg.message,
          position: 'bottom-right',
          dangerouslyUseHTMLString: true,
          onClick: function () {
            if (msg.uri) {
              that.$router.push({path: msg.uri})
              this.close();
            }
          }
        })
      },
      /**
       * ws通信发生错误
       */
      wsErrorHandle(event) {
        //console.log(event, '通信发生错误')
        this.wsInit()
      },
      /**
       * ws关闭
       */
      wsCloseHandle(event) {
        //console.log(event, 'ws关闭')
        this.wsInit()
      },
      /**
       * 销毁ws
       */
      wsDestroy() {
        if (this.webSocket !== null) {
          this.webSocket.removeEventListener('open', this.wsOpenHandle)
          this.webSocket.removeEventListener('message', this.wsMessageHandle)
          this.webSocket.removeEventListener('error', this.wsErrorHandle)
          this.webSocket.removeEventListener('close', this.wsCloseHandle)
          this.webSocket.close()
          this.webSocket = null
          clearInterval(this.wsTimer)
        }
      },
      sendDataToServer() {
        if (this.webSocket.readyState === 1) {
          this.webSocket.send('前端发送数据测试')
        } else {
          throw Error('服务未连接')
        }
      }
    }
  }
</script>
